package org.springblade.common.utils.canal;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.Message;
import lombok.extern.slf4j.Slf4j;
import org.springblade.modules.admin.service.CanalClientService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class MessageHandler {

    @Resource
    private AbstractEntryHandler abstractEntryHandler;

	@Resource
	private CanalClientService canalClientService;

    public void handler(Message message) {
        this.printEntry(message.getEntries());
    }

	private void printEntry(List<CanalEntry.Entry> entrys) {
		for (CanalEntry.Entry entry : entrys) {
			if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN || entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
				continue;
			}

			CanalEntry.RowChange rowChange = null;
			try {
				rowChange = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
			} catch (Exception e) {
				throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(),
					e);
			}

			CanalEntry.EventType eventType = rowChange.getEventType();
			System.err.println(String.format("================&gt; binlog[%s:%s] , name[%s,%s] , eventType : %s",
				entry.getHeader().getLogfileName(), entry.getHeader().getLogfileOffset(),
				entry.getHeader().getSchemaName(), entry.getHeader().getTableName(),
				eventType));

			for (CanalEntry.RowData rowData : rowChange.getRowDatasList()) {
				if (eventType == CanalEntry.EventType.DELETE) {
					printColumn(rowData.getBeforeColumnsList());
				} else if (eventType == CanalEntry.EventType.INSERT) {
					printColumn(rowData.getAfterColumnsList());
				} else {
					System.err.println("------------&gt; before 数据修改前 -----------------");
					printColumn(rowData.getBeforeColumnsList());
					System.err.println("------------&gt; after 数据修改后 -----------------");
					printColumn(rowData.getAfterColumnsList());
				}
			}
			if(eventType != CanalEntry.EventType.DELETE){
				canalClientService.tlwSync(entry.getHeader().getTableName(),rowChange);
			}
		}
	}

	private void printColumn(List<CanalEntry.Column> columns) {
		for (CanalEntry.Column column : columns) {
			System.err.println(column.getName() + " : " + column.getValue() + "    update=" + column.getUpdated());
		}
	}

}
